import axios from '@/services/axios'

const state = {
  token: localStorage.getItem('token'),
  user: null,
  loading: false,
  error: null
}

const mutations = {
  SET_TOKEN(state, token) {
    state.token = token
    if (token) {
      localStorage.setItem('token', token)
    } else {
      localStorage.removeItem('token')
    }
  },
  SET_USER(state, user) {
    state.user = user
  },
  SET_LOADING(state, loading) {
    state.loading = loading
  },
  SET_ERROR(state, error) {
    state.error = error
  },
  CLEAR_ERROR(state) {
    state.error = null
  }
}

const actions = {
  // 登录
  async login({ commit }, credentials) {
    try {
      commit('SET_LOADING', true)
      commit('CLEAR_ERROR')
      console.log('开始登录请求')
      const response = await axios.post('/api/auth/login', credentials)
      const { token, user } = response.data
      console.log('登录成功，用户信息:', user)
      console.log('用户角色:', user.role)
      commit('SET_TOKEN', token)
      commit('SET_USER', user)
      return true
    } catch (error) {
      console.error('登录失败:', error.response?.data || error.message)
      commit('SET_ERROR', error.response?.data?.error || '登录失败')
      return false
    } finally {
      commit('SET_LOADING', false)
    }
  },

  // 注册
  async register({ commit }, userData) {
    try {
      commit('SET_LOADING', true)
      commit('CLEAR_ERROR')
      const response = await axios.post('/api/auth/register', userData)
      return true
    } catch (error) {
      commit('SET_ERROR', error.response?.data?.error || '注册失败')
      return false
    } finally {
      commit('SET_LOADING', false)
    }
  },

  // 获取用户信息
  async getProfile({ commit, dispatch }) { // 添加 dispatch

    try {
      commit('SET_LOADING', true);
      commit('CLEAR_ERROR');
      // 修正 API 路径为 /api/auth/me
      const response = await axios.get('/api/auth/me');

      // 后端 /api/auth/me 直接返回 user 对象，不需要 response.data.user
      if (response.data) { 
        commit('SET_USER', response.data);
      } else {
        // console.error('[AuthStore] getProfile: Invalid response data.'); // 移除日志
        commit('SET_ERROR', '获取用户信息失败：无效的响应');
        // 如果获取用户信息失败，也应该清除登录状态
        dispatch('logout'); // 调用 logout action 清除 token 和 user
        return false;
      }
      return true;
    } catch (error) {
      // console.error('[AuthStore] getProfile: Request failed.', error.response?.data || error.message); // 移除日志
      commit('SET_ERROR', error.response?.data?.error || '获取用户信息失败');
      // 如果获取用户信息失败（例如 token 无效或过期），清除登录状态
      dispatch('logout'); // 调用 logout action 清除 token 和 user
      return false;
    } finally {
      // console.log('[AuthStore] getProfile: Committing SET_LOADING(false).'); // 移除日志
      commit('SET_LOADING', false);
      // console.log('[AuthStore] getProfile: Action finished.'); // 移除日志
    }
  },

  // 更新用户信息
  async updateProfile({ commit }, data) {
    try {
      commit('SET_LOADING', true)
      commit('CLEAR_ERROR')
      // 注意：这里的 API 路径和请求体结构需要与后端匹配
      // 修正 API 路径为 /api/user/profile，使用 PATCH 方法
      const response = await axios.patch('/api/user/profile', data.userData)
      commit('SET_USER', response.data.user) // 假设后端返回 { user: ... }
      return true
    } catch (error) {
      commit('SET_ERROR', error.response?.data?.error || '更新用户信息失败')
      return false
    } finally {
      commit('SET_LOADING', false)
    }
  },

  // 修改密码
  async changePassword({ commit }, data) {
    try {
      commit('SET_LOADING', true);
      commit('CLEAR_ERROR');
      
      // 后端路由是 PUT /api/user/password，不需要 userId
      // 请求体需要 { currentPassword, newPassword }
      await axios.put('/api/user/password', data.passwordData);
      return true;
    } catch (error) {
      commit('SET_ERROR', error.response?.data?.error || '修改密码失败');
      return false;
    } finally {
      commit('SET_LOADING', false);
    }
  },

  // 登出
  logout({ commit }) {
    commit('SET_TOKEN', null)
    commit('SET_USER', null)
    commit('CLEAR_ERROR')
  }
}

const getters = {
  isAuthenticated: state => !!state.token,
  isAdmin: state => state.user?.role === 'admin',
  currentUser: state => state.user,
  userId: state => state.user?._id, // 添加 userId getter
  loading: state => state.loading,
  error: state => state.error,
  token: state => state.token // 添加 token getter
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}